jquery是JavaScript的一套函式庫
jquery裡面有一個東西叫ajax,可以提交按鈕不跳頁、部分畫面更新重整。
應該說用jquery裡面的ajax比較簡單,直接用JavaScript達成同樣目的比較難,參考:
輕鬆理解 Ajax 與跨來源請求
先找js的cdn:
ajax每個項目的說明:
https://api.jquery.com/jquery.ajax/
refresh.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>refresh</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<p>有ajax。時間是:<span class="times"></span></p>
<script>
setInterval(function() {
Autofresh();
}, 2000);
function Autofresh() {
$.ajax({
url: 'time.jsp',
type: 'POST',
//data: ,
success: function(data) {
console.log('Submission was successful.');
console.log(data);
var start = data.indexOf("<times>");
var end = data.indexOf("</times>");
var times = data.substring(start + 7, end).trim();
$(".times").html("");
$(".times").html(times);
},
error: function(XMLHttpRequest, status, error) {
console.log(error)
}
})
}
Autofresh();
</script>
</body>
</html>
time.jsp:
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<%@ page import="java.util.*" %>
<%@ page import="java.text.*" %>
<times >
<%
Date dNow = new Date( );
SimpleDateFormat fd = new SimpleDateFormat ("yyyy-MM-dd");
SimpleDateFormat ft = new SimpleDateFormat ("HH:mm:ss");
String date = fd.format(dNow);
String time = ft.format(dNow);
out.println(date+" "+time);
%>
</times>
結果:
pass_value.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>pass_value</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
setInterval(function() {
Autofresh();
}, 2000);
function Autofresh() {
$.ajax({
url: 'get_value.jsp',
type: 'POST',
data: {
"HelloWorld": 'HelloWorld123',
},
success: function(data) {
console.log(data);
},
error: function(XMLHttpRequest, status, error) {
console.log(error)
}
})
}
Autofresh();
</script>
</body>
</html>
get_value.jsp
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<%
String hello= request.getParameter("HelloWorld").trim();
out.println(hello);
%>
結果(pass_value.html):